(function () {
    var core = ecui,
        dom = core.dom,
        util = core.util,
        ready = false;

    function showOrders() {
        var monthView = core.get('venue-order-month-view'),
            current = NS.data.calendar[monthView.getSelected().getDate().getDate() - 1],
            month_head = ecui.$('month_head');

        ecui.$('calendarOrderAdd').href = '#/venueOrder/edit~orderType=1~day=' + ecui.util.formatDate(monthView.getDate(), 'yyyy-MM-dd') + '~DENY_CACHE';

        core.get('venue-order-list-view').removeAll(true);
        if (current.projectRoundList) {
            var html = ['<li class="site-item" style="height: ' + month_head.clientHeight + 'px"></li>'],
                el = core.dom.create();
            current.projectRoundList.forEach(function (item) {
                html.push(ecui.esr.getEngine().getRenderer('venue_orderItem')({item: item, day: current.day}));
            });
            el.innerHTML = html.join('');
            core.get('venue-order-list-view').add(core.dom.children(el));
        }
    }

    NS.ui.FilterPopupButton = core.inherits(
        mao.ui.PopupButton,
        {
            onconfirm: function () {
                ecui.esr.getRoute(ecui.esr.getLocation().split('~')[0]).refresh();
            }
        }
    );

    NS.ui.MonthView = core.inherits(
        core.ui.MonthView,
        {
            /**
             * @override
             */
            $ready: function (event) {
                ecui.ui.MonthView.prototype.$ready.call(this, event);

                core.addGestureListeners(this, {
                    swipeleft: this.swipeleft.bind(this),
                    swiperight: this.swiperight.bind(this)
                    // swipeup: this.swipeup.bind(this),
                    // swipedown: this.swipedown.bind(this)
                });
            },
            $dateclick: function (event) {
                core.ui.MonthView.prototype.$dateclick.call(this, event);
                showOrders();
            },
            swipeleft: function () {
                this.setDate(new Date(this.getYear(), this.getMonth(), 1));
            },
            swiperight: function () {
                this.setDate(new Date(this.getYear(), this.getMonth() - 2, 1));
            },
            swipeup: function (event) {
                if (this.contain(event.active) && this._bCollapsed) {
                    var cells = this.getDays(),
                        index = cells.indexOf(this.getSelected());
                    for (var i = 0; cells[i]; i = i + 7) {
                        if (i > index || i + 6 < index) {
                            for (var j = 0; j < 7; j++) {
                                dom.removeClass(cells[i + j].getMain(), 'ui-hide');
                            }
                        }
                    }
                    this._bCollapsed = false;
                    ecui.get('venue-order-list-view').resize();
                }
            },
            swipedown: function (event) {
                if (this.contain(event.active) && !this._bCollapsed) {
                    var cells = this.getDays(),
                        index = cells.indexOf(this.getSelected());
                    for (var i = 0; cells[i]; i = i + 7) {
                        if (i > index || i + 6 < index) {
                            for (var j = 0; j < 7; j++) {
                                dom.addClass(cells[i + j].getMain(), 'ui-hide');
                            }
                        }
                    }
                    this._bCollapsed = true;
                    ecui.get('venue-order-list-view').resize();
                }
            },
            onmousedown: function (event) {
                ecui.dispatchEvent(ecui.get('venue-order-list-view'), 'activate', event);
            },
            initHeightFn: function () {
                var body = this.getMain().firstChild.lastChild;
                body.style.height = '';
                this.initHeight = body.offsetHeight;
                this.moveHeight = body.offsetHeight - body.firstChild.offsetHeight;
            },
            setView: function (year, month) {
                ecui.ui.MonthView.prototype.setView.call(this, year, month);
                this.initHeightFn();
                core.esr.setData('CalendarTitle', year + '.' + (month < 10 ? '0' + month : month));
                if (NS.data.venues) {
                    //TODO 填入时间的ＦＯＲＭ
                    core.esr.getRoute('calendar').refresh();
                }
            }
        }
    );
    NS.ui.ListViewControl = core.inherits(
        ecui.ui.Control,
        {
            onmousedown: function (event) {
                ecui.dispatchEvent(ecui.get('venue-order-list-view'), 'activate', event);
            }
        }
    );

    NS.ui.MListView = core.inherits(
        ecui.ui.MListView,
        {
            clearTimer: util.blank,
            setPosition: function (x, y) {
                x = 0;
                ecui.ui.MListView.prototype.setPosition.call(this, x, y);

                var monthView = ecui.get('venue-order-month-view'),
                    addBtn = ecui.$('calendarOrderAdd'),
                    tbody = monthView.getMain().firstChild.lastChild,
                    top = monthView.getSelected() ? monthView.getSelected().getMain().offsetTop : 0;

                tbody.style.height = Math.max(Math.min(monthView.initHeight, monthView.initHeight + y), monthView.initHeight - monthView.moveHeight) + 'px';
                tbody.scrollTop = Math.min(top, -y);
                if (!dom.hasClass(addBtn, 'collect')) {
                    dom.addClass(addBtn, 'collect');
                }
                this.clearTimer();
                this.clearTimer = util.timer(function () {
                    dom.removeClass(addBtn, 'collect');
                }, 300, this);
            },
            $footercomplete: function (event) {
                ecui.ui.MListView.prototype.$footercomplete.call(this, event);
            }
        }
    );

    NS.ui.VenueFilterSelectEdit = core.inherits(
        mao.ui.SelectEdit,
        {
            onchange: function (event) {
                var item = event.item ? event.item : {},
                    text = event.item._sText,
                    value = event.item._sValue,
                    form = document.forms.venue_order_search_form;
                if (item.yardId) {
                    text += ' - ' + item.yardName;
                    form.yardId.value = item.yardId;
                }
                form.venueId.value = value;
                this.setValue(item.venueId || item.yardId);
                this.setText(text);
                this.alterStatus((this.getValue() === '' ? '+' : '-') + 'placeholder');
                dom[this.getValue() === '' ? 'addClass' : 'removeClass'](this.getMain(), 'placeholder');
                util.timer(function () {
                    ecui.esr.getRoute(ecui.esr.getLocation().split('~')[0]).refresh();
                }, 100, this);
            },
            setPlaceholder: function () {
                this._eText.innerHTML = '全国';
            }
        }
    )

    util.extend(NS.data, {
        venues: [],
        sortBarConfigs: [
            { type: 'venue', typeName: '场馆', active: false, show: false, target: 'venue_selected', data: [] },
            { type: 'status', typeName: '筛选', active: false, show: false, target: 'status_selected', data: {}}
        ],
        status: {
            orderType: { value: '', title: '订单状态', select: '', items: [{ value: '', code: '全部' }, { value: '1', code: '预定场' }, { value: '2', code: '已定场' }] },
            yardAttribute: { value: '', title: '演出场地', select: '', items: [{ value: '', code: '全部' }, { value: '1', code: '主厅' }, { value: '2', code: '副厅' }] },
            actionCutting: { value: '', title: '演出场次', type: 'checkbox', select: '', items: [{ value: '1', code: '日场' }, { value: '3', code: '晚场' }, { value: '2', code: '夜场' }] },
            contractType: { value: '', title: '合同类型', select: '', items: [{ value: '', code: '全部' }, { value: '1', code: '包场' }, { value: '2', code: '分票' }, { value: '3', code: '商务' }, { value: '4', code: '自办' }] },
            dayActionCutting: { value: '', title: '单日场次', type: 'slide', select: '', items: [], scale: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '不限'] }
        }
    });

    function getStatus (item) {
        var res = {
            'roundState': 0,
            'desc': '预定'
        };
        if (+item.finance.id) {
            if (item.finance.isCreateVoucher === 2) {
                // 凭证已生成
                res.roundState = 12;
                res.desc = '凭证已生成';
            } else if (item.finance.isCreateVoucher === 3) {
                // 凭证生成中
                res.roundState = 11;
                res.desc = '凭证生成中';
            } else {
                switch (item.finance.auditState) {
                    // 结算单待审核
                    case 1:
                        res.roundState = 8;
                        res.desc = '结算单审批中';
                        break;
                    // 结算单待创建
                    case 2:
                    case 5:
                        res.roundState = 9;
                        res.desc = '结算单待建';
                        break;
                    // 结算单审批通过
                    case 3:
                        res.roundState = 10;
                        res.desc = '结算单通过';
                        break;
                } 
            }
        } else if (+item.roundTicket.id) {
            res.roundState = 7;
            res.desc = '票务已创建';
        } else if (+item.order.id) {
            switch (item.order.auditState) {
                // 订单待审核
                case 1:
                    res.roundState = 4;
                    res.desc = '订单审批中';
                    break;
                // 订单待创建
                case 2:
                case 5:
                    res.roundState = 5;
                    res.desc = '订单待建';
                    break;
                // 订单审批通过
                case 3:
                    res.roundState = 6;
                    res.desc = '订单通过';
                    break;
            }
        } else if (+item.contract.id) {
            switch (item.contract.auditState) {
                // 合同待审核
                case 1:
                    res.roundState = 1;
                    res.desc = '合同审批中';
                    break;
                // 合同待创建
                case 2:
                case 5:
                    res.roundState = 2;
                    res.desc = '合同待建';
                    break;
                // 合同审批通过
                case 3:
                    res.roundState = 3;
                    res.desc = '合同通过';
                    break;
            }
        }
        return res;
    }
    core.esr.addRoute('calendar', {
        model: [''],
        frame: true,
        weight: 2,
        onbeforerequest: function (context) {
            ecui.get('order-venue').getMain().innerHTML = '全国';
        },
        onbeforerender: function (context) {
            NS.data.sortBarConfigs[0].data = context.venues || [];
            NS.data.sortBarConfigs[1].data = NS.data.status;
            NS.data.venues = context.venues || [];
            if (this.day) {
                context.day = ecui.util.formatDate(this.day, 'yyyy-MM-dd');
                delete this.day;
            }
            if (this.venueId) {
                context.venueId = this.venueId;
                delete this.venueId;
            }
            if (this.venueName) {
                ecui.get('order-venue').getMain().innerHTML = this.venueName;
                delete this.venueName;
            }
        },
        onafterrender: function (context) {
        },
        oncached: function () {

        },
        onleave: function () {

        },
        refresh: function () {
            var monthView = ecui.get('venue-order-month-view'),
                month = monthView.getYear() + '-' + String.prototype.slice.call('0' + monthView.getMonth(), -2),
                form = document.forms.venue_order_search_filter_form;

            ecui.esr.setData('month', month.replace('-', '年') + '月');
            ecui.esr.request(
                [
                    util.stringFormat('calendar@FORM /erp-management/venue/order/calendar/list?venue_order_search_form&month={0}{1}', month, form ? '&' + form.name : ''),
                    util.stringFormat('venues@JSON /erp-management/venue/select-list-tree?month={0}', month)
                ],
                function () {
                    var calendar = core.esr.getData('calendar');
                    var venues = core.esr.getData('venues');
                    ecui.get('order-venue')._oItems = venues;
                    NS.data.venues = venues;
                    NS.data.calendar = calendar;

                    if (calendar instanceof Object) {
                        var cells = monthView.getDays(),
                            day1 = cells[0].getDate(),
                            index = 0,
                            type1 = 0,
                            type2 = 0;
                        index = new Date(day1.getFullYear(), day1.getMonth() + 1, 0).getDate() + 1 - day1.getDate();

                        index = index > 7 ? 0 : index;
                        cells = cells.slice(index, index + calendar.length);
                        calendar.forEach(function (day, i) {
                            if (day.projectRoundList) {
                                var count = 0,
                                    el = cells[i].getMain(),
                                    isPreview;
                                day.projectRoundList.forEach(function (item) {
                                    Object.assign(item, getStatus(item));
                                    // 统计意向、锁定数量
                                    if ((item.roundState === 0 || item.roundState === 1) && !item.state) {
                                        type1++;
                                        isPreview = true;
                                    } else {
                                        type2++;
                                    }
                                    var h = new Date(item.startTime).getHours()
                                    if (h >= 6 && h < 16) {
                                        item.actionCutting = 1;
                                    } else if (h >= 16 && h < 23) {
                                        item.actionCutting = 2;
                                    } else {
                                        item.actionCutting = 3;
                                    }
                                    count++;
                                });

                                // 添加场数标记
                                // core.dom.removeClass(el, 'count-1 count-2 count-3 count-4-9 count-10-19 count-max');
                                // if (count === 1) {
                                //     core.dom.addClass(el, 'count-1');
                                // } else if (count === 2) {
                                //     core.dom.addClass(el, 'count-2');
                                // } else if (count === 3) {
                                //     core.dom.addClass(el, 'count-3');
                                // } else if (count >= 4 && count <= 9) {
                                //     core.dom.addClass(el, 'count-4-9');
                                // } else if (count >= 10 && count <= 19) {
                                //     core.dom.addClass(el, 'count-10-19');
                                // } else if (count >= 20) {
                                //     core.dom.addClass(el, 'count-max');
                                // }
                                if (el) {
                                    el.setAttribute('data-count', count > 0 ? count + '场' : '');

                                    if (isPreview) {
                                        core.dom.addClass(el, 'preview');
                                    } else {
                                        core.dom.removeClass(el, 'preview');
                                    }
                                    core.dom.removeClass(el, util.stringFormat('small type-{0} type-{1} type-{2} type-{3} type-{4}', undefined, 0, 1, 2, 3));
                                    core.dom.addClass(el, 'type-' + day.type);
                                    if (day.typeDesc) {
                                        el.innerHTML = day.typeDesc;
                                        if (day.typeDesc.length > 2) {
                                            core.dom.addClass(el, 'small');
                                        }
                                    }
                                }
                            }
                        });
                        core.esr.setData('PreviewCount', type1);
                        core.esr.setData('OrderCount', type2);
                        core.esr.setData('TotalCount', type1 + type2);

                        showOrders();
                    }
                },
                function () {
                    // debugger
                }
            );
        }
    });

}());